package com.lry.event;

import com.lry.proxy.Invoker;
import com.lry.proxy.RpcInvoker;
import com.lry.rpc.netty.BeanKey;
import com.lry.rpc.netty.client.ChannelWrapper;
import com.lry.rpc.netty.client.ClientCache;
import com.lry.rpc.netty.client.Connector;
import io.netty.channel.Channel;

import java.net.InetSocketAddress;
import java.util.Iterator;
import java.util.List;

public class ProviderChangeListener implements RpcListener<ProviderChangeEvent>{

    /**
     *
     * @param providerChangeEvent
     * @return
     */
    @Override
    public boolean callback(ProviderChangeEvent providerChangeEvent) {

        ProviderChangeWrapper providerChangeWrapper = providerChangeEvent.getProviderChangeWrapper();
        String serviceName = providerChangeWrapper.getServiceName();
        String implName = providerChangeWrapper.getImplName();
        List<ProviderNodeWrapper> nodes = providerChangeWrapper.getNodes();

        for (ProviderNodeWrapper node : nodes) {
            BeanKey beanKey = new BeanKey(serviceName,implName,node.getVersion());
            List<Invoker> cacheInvokes = ClientCache.getInvokers(beanKey, node.getGroup());


            Iterator<Invoker> it = cacheInvokes.iterator();
            while(it.hasNext()){
                Invoker next = it.next();
                boolean f = true;
                for (ProviderNodeWrapper node1 : nodes) {
                    if(node1.getIp().equals(next.getIps())){
                        f = false;
                        break;
                    }
                }
                if(f){
                    it.remove();
                }
            }


            for (ProviderNodeWrapper node1 : nodes) {
                BeanKey beanKey1 = new BeanKey(serviceName,implName,node1.getVersion());
                Invoker invoker = ClientCache.getInvoker(beanKey1, node1.getGroup(),node1.getIp());
                String ip = node1.getHost();
                Integer port = node1.getPort();

                if(null==invoker || !invoker.isAvailable()){
                    Channel channel = Connector.connect(InetSocketAddress.createUnresolved(ip, port));
                    ChannelWrapper newChannelWrapper = ChannelWrapper.builder().channel(channel).ip(ip).port(port).weight(node1.getWeight()).build();
                    Invoker rpcInvoker = new RpcInvoker(newChannelWrapper);
                    cacheInvokes.add(rpcInvoker);
                }
            }

        }


        return true;
    }




}
